package com.ruoyi.framework.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.protocol.PacketReceivedTimeHolder;
import com.ruoyi.common.entity.LoginUser;
import com.ruoyi.common.entity.system.SysDept;
import com.ruoyi.common.entity.system.SysRole;
import com.ruoyi.common.entity.system.SysUser;
import com.ruoyi.common.enums.ExceptionEnum;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BizException;
import com.ruoyi.system.entity.SysUserRole;
import com.ruoyi.system.mapper.SysRoleDeptMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户验证处理
 *
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("user_name",username));
        if (Objects.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new BizException(ExceptionEnum.LOGIN_FAIL,"登录用户：" + username + " 不存在");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BizException(ExceptionEnum.LOGIN_FAIL,"对不起，您的账号：" + username + " 已停用");
        }
        List<SysUserRole> sysUserRoles=sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id",user.getUserId()));
        List<Long> roleIds=sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRole> sysRoles=sysRoleService.list(new QueryWrapper<SysRole>().in("role_id",roleIds));
        //给用户设置角色信息
        user.setRoles(sysRoles);
        //给用户设置部门信息
        SysDept sysDept = sysDeptService.getOne(new QueryWrapper<SysDept>().eq("dept_id", user.getDeptId()));
        if (Objects.nonNull(sysDept)){
            user.setDept(sysDept);
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
